'use client';

import { useEffect, useRef } from 'react';
import 'highlight.js/styles/github-dark.css';
import hljs from 'highlight.js';

// 注册Vue语言支持
import vue from 'highlight.js/lib/languages/xml';
hljs.registerLanguage('vue', vue);

interface MarkdownContentProps {
  content: string;
}

export default function MarkdownContent({ content }: MarkdownContentProps) {
  const contentRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.innerHTML = content;
      
      // 为标题元素添加唯一ID和锚点链接，避免与TableOfContents组件冲突
      const headings = contentRef.current.querySelectorAll('h2, h3');
      headings.forEach((heading, index) => {
        // 使用前缀确保ID唯一性
        const headingId = `content-heading-${index}`;
        heading.id = headingId;
        
        // 添加锚点链接
        const anchor = document.createElement('a');
        anchor.href = `#${headingId}`;
        anchor.className = 'anchor';
        anchor.innerHTML = '#';
        if (!heading.querySelector('.anchor')) {
          heading.insertBefore(anchor, heading.firstChild);
        }
      });
      
      // 找到所有代码块并应用高亮
      const codeBlocks = contentRef.current.querySelectorAll('pre code');
      codeBlocks.forEach((block) => {
        hljs.highlightElement(block as HTMLElement);
      });
    }
  }, [content]);

  return <div ref={contentRef} className="markdown-content" />;
}